package processor

import (
	"fmt"
	"os/exec"
	"vidproc/internal/config"
	"vidproc/pkg/ffmpeg"
)

type VideoProcessor interface {
	GenerateLowQuality(input, output string) error
	GenerateWebM(input, output string) error
	GeneratePoster(input, output string) error
}

type videoProcessor struct {
	config *config.VideoConfig
}

func NewVideoProcessor(cfg *config.VideoConfig) VideoProcessor {
	return &videoProcessor{
		config: cfg,
	}
}

func (vp *videoProcessor) GenerateLowQuality(input, output string) error {
	args := ffmpeg.NewFFmpegCommandBuilder().
		Input(input).
		VideoCodec(vp.config.VideoSettings.Low.Codec).
		AudioCodec("aac").
		Resolution(vp.config.VideoSettings.Low.Resolution).
		Bitrate(vp.config.VideoSettings.Low.Bitrate).
		FPS(vp.config.VideoSettings.Low.FPS).
		Preset(vp.config.VideoSettings.Low.Preset).
		CRF(vp.config.VideoSettings.Low.CRF).
		Output(output).
		Build()

	cmd := exec.Command(args[0], args[1:]...)
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("failed to generate low quality video: %v", err)
	}
	return nil
}

func (vp *videoProcessor) GenerateWebM(input, output string) error {
	args := ffmpeg.NewFFmpegCommandBuilder().
		Input(input).
		VideoCodec(vp.config.VideoSettings.WebM.Codec).
		AudioCodec("libopus").
		Resolution(vp.config.VideoSettings.WebM.Resolution).
		Bitrate(vp.config.VideoSettings.WebM.Bitrate).
		FPS(vp.config.VideoSettings.WebM.FPS).
		Quality(vp.config.VideoSettings.WebM.Quality).
		CPUUsed(vp.config.VideoSettings.WebM.CPUUsed).
		Output(output).
		Build()

	cmd := exec.Command(args[0], args[1:]...)
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("failed to generate WebM video: %v", err)
	}
	return nil
}

func (vp *videoProcessor) GeneratePoster(input, output string) error {
	args := ffmpeg.NewFFmpegCommandBuilder().
		SeekTime(vp.config.PosterSettings.Time).
		Input(input).
		VideoCodec("libwebp").
		Resolution(vp.config.PosterSettings.Size).
		Frames(1).
		Quality(fmt.Sprintf("%d", vp.config.PosterSettings.Quality)).
		CompressionLevel(6).
		Lossless(false).
		Output(output).
		Build()

	cmd := exec.Command(args[0], args[1:]...)
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("failed to generate poster: %v", err)
	}
	return nil
}
